import pandas as pd
import requests
import time
import json
import datetime
def save_json(file,res):
    """
    保存 dict 到本地json 文件 ， 自动创建json
    :param file: json 文件名
    :param res: 数据
    :return:
    """
    with open(file, 'w', encoding='utf-8') as wr:
        json.dump(res, wr, ensure_ascii=False, indent=2)

def load_json(file):
    """
    读取本地json文件，得到dict
    :param file: json 文件名
    :return:
    """
    with open(file, 'r', encoding='utf-8') as reader:
        res = json.load(reader)
    return res


def save_stock_dict(stock_csv = 'stocklist.csv',output_json = 'stock_code2name.json'):
    """
    生成股票 code 和名字的 json
    :return:
    """
    df =pd.read_csv(stock_csv)
    df_ = df
    names = {}
    df_['code'] = df_['stkcd'].apply(lambda x : x[2:])
    for k, v in zip(df['code'],df['stknm']):
        names[k] = v
    save_json(output_json,names)

def get_date_str():
    """
    30天日期
    :return:
    """
    ds =30
    today_str = datetime.datetime.today().strftime("%Y%m%d")
    start = datetime.datetime.today() - datetime.timedelta(days=ds)
    start_str = start.strftime("%Y%m%d")
    return start_str,today_str

def history(code,start,end):
    """

    :param code:  股票代码
    :param start: 开始日期  20210101
    :param end:    结束日期  20210102
    :return:
    """
    url = 'https://q.stock.sohu.com/hisHq?code=cn_{}&start={}&end={}'
    rsp = requests.get(url.format(code,start,end))
    if isinstance(rsp.json(),dict):
        # 需要list
        return []
    if 'hq' not in rsp.json()[0]:# 需要有 hq字段 否则[0]['hq']报错
        return []
    datas = rsp.json()[0]['hq']
    """
    日期,
    今日开盘价,
    今日收盘价,
    涨跌幅度，
    涨跌百分比,
    今日最低价,
    今日最高价，
    今日成交股票手数,
    今日成交金额(单位：万)
    换手率
    """
    return datas


def save_hist(codes,file_name ):
    """
    存储历史股票表现
    :param df_:
    :return:
    """
    if not isinstance(codes,list):
        print('plz input a list')
        return
    if len(codes) == 0:
        print('len of codes = 0')
        return

    res =  {}
    for ix, code in enumerate(codes):
        if ix % 100 == 0:
            print(ix)
        res_ = history(code,"20210802","20210803")
        res[code] = res_

    save_json(file_name,res)


def run_ranking():
    # 按涨幅排序
    hists = load_json('stock_hist.json')
    code2name = load_json('stock_code2name.json')
    datas = []
    for code , name in code2name.items():
        if  hists[code] == []:
            continue
        hist_ = hists[code][:5] # 第一天的数据 历史数据是从近到远
        percent = float(hist_[0][2]) / float(hist_[-1][1]) -1 # 最后一天 除以第一天 -1 = 涨幅
        datas.append((code,name,round(100*percent,2)))
        #print('----')
    # 按涨幅排序
    datas = sorted(datas,key= lambda x: x[-1],reverse=True)
    for d in datas[:200]:
        print(d)